package com.my.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.my.model.admin.dtos.UserAuditDto;
import com.my.model.common.dtos.ResponseResult;
import com.my.model.common.enums.AppHttpCodeEnum;
import com.my.model.user.dtos.LoginDto;
import com.my.model.user.pojos.ApUser;
import com.my.user.mapper.ApUserMapper;
import com.my.user.service.ApUserService;
import com.my.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;


@Service
@Transactional
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    /**
     * app端登录功能
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //1.正常登录 用户名和密码
        if(!dto.getPhone().isEmpty() && !dto.getPassword().isEmpty()){
            //1.1根据用户名获取用户信息
            LambdaQueryWrapper<ApUser> lqw = new LambdaQueryWrapper<>();
            lqw.eq(ApUser::getPhone,dto.getPhone());
            ApUser user = this.getOne(lqw);

            //1.2没有该用户信息
            if(user == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户信息不存在");
            }

            //1.3比对用户密码
            String password = user.getPassword();
            String salt = user.getSalt();
            String loginPassword = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes(StandardCharsets.UTF_8));
            if(!loginPassword.equals(password)) {
                //密码不正确
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
            }

            //1.4查看用户状态
            if(user.getStatus()) {
                //用户被锁定
                return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH,"用户已被锁定");
            }

            //1.5设置token
            String token = AppJwtUtil.getToken(user.getId().longValue());
            Map<String,Object> map = new HashMap<>();
            map.put("token",token);
            map.put("user",user);
            return ResponseResult.okResult(map);
        }else {
            //2.游客登录
            Map<String,Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
    }


}
